import { useState, useEffect } from 'react';
import { Modal, Popover, Switch, Upload, message, Popconfirm, Button } from 'antd';
import { EditOutlined } from '@ant-design/icons';
import OperaBtnRender from '@/components/OperaBtnRender';
import TableRender from '@/components/TableRender';
import { isEmpty, findIndex } from 'lodash';
import { QuestionCircleOutlined } from '@ant-design/icons';
import StoreEditModal from './StoreEditModal';
import StoreNotesModal from './StoreNotesModal';
import CustomizeModal from './CustomizeModal';
import CustomizeModalRemark from './CustomizeModalRemark';
import SortAreaCodeModal from './SortAreaCodeModal';
import DataSyncModal from './DataSyncModal';
import BatchSetSwitch from './BatchSetSwitch';
import BatchSetPrint from './BatchSetPrint';
import BatchSetPay from './BatchSetPay';
import PushRobot from './PushRobot';
import { getToken } from '@/utils/authority';
import { Base64 } from 'js-base64';
import { httpChange } from '@/utils/utils.jsx';
import Iconfont from '@/components/IconFont';
import { queryAreaCode, batchUpdateUnpickDisplay, batchUpdateOfflinePaySwitch } from '../service';
import styles from './index.module.less';
import { useResize } from '@/hooks/useResize';
import { getCurrentUser, checkIsProd, isDianaUser } from '@/utils/authority';
import CommonLoading from '@/components/CommonLoading';
import { searchOrderByIds, getFieldConfig, searchOrderShipByIds, updateFieldConfig } from './services';
import EditColumns from '@/pages/OrderModule/orderList/components/OrderList/components/RightAction/EditColumns'
import { debounce } from 'lodash';
import BatchImport from "@/pages/GoodsModule/memberPrice/components/Actions/BatchImport/indexSupply";

const clientId = 'sword'; // 客户端id
const clientSecret = 'sword_secret'; // 客户端密钥

const headers = {
  Authorization: `Basic ${Base64.encode(`${clientId}:${clientSecret}`)}`,
  'Blade-Auth': getToken(),
};

const merchantAreaCodeMap = {
  NT: '南通',
  CS: '常熟',
  ZL: '织里'
}

const duShangUuid = [390078, 3001213, 374793]; //杜尚uuid展示企业机器人 3001213 374793(测试)

//是否是生产环境
const isProd = checkIsProd();
//后三个线上用户

const StoreList = ({
  data,
  headerHeight,
  roleList,
  selectedRow,
  updateSelectRow,
  selectedRowId,
  updateSelectedRowId,
  handleStoreList,
  handleTableImport,
  offlinePaymentShow,
  handleTableExport,
  clearSelect,
  upDateSwitch,
  updateStraightFactorySwitch,
  updateAutoPushSwitch,
  updateDataSyncSwitch,
  updateDeductionSwitch,
  batchSetPrintPush,
  total,
  query,
  pages,
  setPages,
  handlUpdateDaiNaSwitch
}) => {
  // 编辑弹窗操作
  const [visible, setVisible] = useState(false);
  const [item, setItem] = useState({}); // 编辑数据
  const [roleType, setRoleType] = useState(0);

  //自定义地址弹框
  const [customizeVisible, setCustomizeVisible] = useState(false);
  const [customizeVisibleRemark, setCustomizeVisibleRemark] = useState(false);
  const [shopRemark, setShopRemark] = useState('');
  const [address, setAddress] = useState('');
  const [storeId, setStoreId] = useState();

  // 备注弹框操作
  const [visibleNote, setVisibleNote] = useState(false);
  // 备注弹框操作
  const [visibleSort, setVisibleSort] = useState(false);
  //抵扣开关弹窗
  const [visibleSwitch, setVisibleSwitch] = useState(true);
  //企微推送机器人弹窗
  const [robotVisible, setRobotVisible] = useState(false);
  //批量设置线下支付弹框
  const [payVisible, setPayVisible] = useState(false);

  const [id, setId] = useState([]);
  const [note, setNote] = useState(undefined);
  const [length, setLength] = useState(0);

  //批量设置推送打印弹框
  const [printVisible, setPrintVisible] = useState(false);

  //批量待拿货数据同步
  const [dataSyncVisible, setDataSyncVisible] = useState(false);

  const is_zjf_user = localStorage.getItem('ISZJF') || sessionStorage.getItem('ISZJF'); //找家纺仓库用户

  const showDaifaTool = !isProd || isDianaUser(getCurrentUser().uuid); //是否展示设置代拿按钮

  const showRobot = !isProd || duShangUuid.includes(getCurrentUser().uuid); //列表是否展示企微机器人

  const [totalAreaList, setTotalAreaList] = useState([]);

  //监听变更
  const { el: btnEl, height: btnHeight } = useResize();

  useEffect(() => {
    visibleSwitch && setVisibleSwitch(false);
    printVisible && setPrintVisible(false);
  }, [data])

  useEffect(() => {
    queryAreaCodeList();
  }, [])

  const queryAreaCodeList = async () => {
    const { data, success } = await queryAreaCode({ areaCode: '' });
    if (success) {
      setTotalAreaList(data);
    }
  }

  const columns = [
    {
      title: '序号',
      name: '序号',
      code: 'noNumber',
      render: (_, record, index) => index + 1,
      width: 60, // 配置列宽，保存到后台
      checked: true, lock: true
    },
    {
      title: '城市',
      name: '城市',
      code: 'merchantAreaCode',
      width: 112,
      render: (text) => (<>{merchantAreaCodeMap[text]}</>),
      checked: true, lock: false
    },
    {
      title: '供应商',
      name: '供应商',
      code: 'storeName',
      width: 112,
      checked: true, lock: false
    },
    {
      title: '门店名称',
      name: '门店名称',
      code: 'shopName',
      width: 140,
      checked: true, lock: false
    },
    {
      title: '门店区域',
      name: '门店区域',
      code: 'storeArea',
      width: 140,
      checked: true, lock: false
    },
    {
      title: '档口号',
      name: '档口号',
      code: 'shopCode',
      width: 140,
      checked: true, lock: false
    },
    {
      title: '供应商类型',
      name: '供应商类型',
      code: 'type',
      width: 120,
      render: (text) => (text == 1 ? '代发' : '供应商直发'),
      checked: true, lock: false
    },
    {
      title: (
        <div>
          <span>
            直发订单
            <br />
            开启用户自发快递
          </span>
          <Popover
            content={
              <span style={{ display: 'block', width: '186px' }}>
                开启：则表示只支持该供应商使用自己的自发快递进行发货
                <br />
                关闭：则表示只支持供应商的快递进行发货
              </span>
            }
            title={null}
          >
            <QuestionCircleOutlined
              style={{ color: '#999', marginLeft: '8px' }}
            />
          </Popover>
        </div>
      ),
      name:'直发订单开启用户自发快递' ,
      code: 'storeZhifa',
      width: 220,
      render: (text, record) => (
        <Switch
          onChange={() => updateStraightFactorySwitch(record.storeId)}
          checkedChildren="已开启"
          unCheckedChildren="已关闭"
          checked={text == 1 ? true : false}
        />
      ),
      checked: true, lock: false
    },
    {
      title: (
        <div>
          <span>自动推送门店打印</span>
          <Popover
            content={
              <span style={{ display: 'block', width: '186px' }}>
                已开启：则表示只支持把订单自动推送给该供应商进行打印订单
                <br />
                已关闭：则表示不允许订单推送给该供应商进行打印
              </span>
            }
            title={null}
          >
            <QuestionCircleOutlined
              style={{ color: '#999', marginLeft: '8px' }}
            />
          </Popover>
        </div>
      ),
      name: '自动推送门店打印',
      code: 'autoPush',
      width: 220,
      render: (text, record) => (
        <Switch
          onChange={() => updateAutoPushSwitch(record, record.storeId)}
          checkedChildren="已开启"
          unCheckedChildren="已关闭"
          checked={text == 1 ? true : false}
        />
      ),
      checked: true, lock: false
    },
    {
      title: (
        <div>
          <span>待拿货数据是否同步供应商</span>
          <Popover
            content={
              <span style={{ display: 'block', width: '186px' }}>
                已开启：供应商能够看到待拿货数量和金额；
                <br />
                已关闭：供应商无法看到待拿货数量和金额
              </span>
            }
            title={null}
          >
            <QuestionCircleOutlined
              style={{ color: '#999', marginLeft: '8px' }}
            />
          </Popover>
        </div>
      ),
      name: '待拿货数据是否同步供应商',
      code: 'unpickDisplay',
      width: 220,
      render: (text, record) => (
        <Switch
          onChange={(e) => {
            if (record.autoPush == 1 && !e) {
              Modal.info({
                content: '自动推送订单打印已开启，不允许关闭',
              });
              return
            }
            updateDataSyncSwitch(record)
          }
          }
          checkedChildren="已开启"
          unCheckedChildren="已关闭"
          checked={text == 1 ? true : false}
        />
      ),
      checked: true, lock: false
    },
    {
      title: '采购付款节点',
      name: '采购付款节点',
      code: 'checkPayTime',
      width: 120,
      render: text => text ? '清点时结算' : '采购时结算',
      checked: true, lock: false
    },
    {
      title: (
        <div>
          <span>退款抵扣</span>
          <Popover
            content={
              <span>
                开启：需要申请商户通过后方可开启，退货金额将不再入账，会在下次备货或采购时做抵扣处理
                <br />
                关闭：保持现状退货成功后，退款金额到账，关闭后再次开启需要商户再次审核
              </span>
            }
            title={null}
          >
            <QuestionCircleOutlined
              style={{ color: '#999', marginLeft: '8px' }}
            />
          </Popover>
        </div>
      ),
      name: '退款抵扣',
      code: 'deductionState',
      width: 220,
      render: (text, record) => (
        //存在未申请但是已开通的数据，注意，deductionState：0未申请 10审核中 20已通过 30已拒绝
        text == 10 ?
          <span className="common-color13">审核中</span>
          :
          <Popconfirm placement="topLeft" title={record.deductionSwitch ? '是否确认取消退款抵扣操作' : '是否确认申请 退款抵扣操作'} onConfirm={() => updateDeductionSwitch(record.storeId, record.deductionSwitch ? 0 : 1)} okText="确定" cancelText="取消">
            <Switch
              checkedChildren="已开启"
              unCheckedChildren="已关闭"
              checked={record.deductionSwitch}
            />
          </Popconfirm>
      ),
      checked: true, lock: false
    },
    {
      title: '联系电话',
      name: '联系电话',
      code: 'shopPhone',
      width: 150,
      checked: true, lock: false
    },
    {
      title: '门店地址',
      name: '门店地址',
      code: 'shopAddress',
      width: 220,
      checked: true, lock: false
    },
    {
      title: '自定义地址',
      name: '自定义地址',
      code: 'shopCustomAddress',
      width: 200,
      render: (text, record) => (
        <div
          style={{
            display: 'flex',
            flexDirection: 'row',
            justifyContent: 'between-around',
          }}
        >
          <Popover content={<div>{text}</div>}>
            <div className={styles.customize}>{text}</div>
          </Popover>
          <EditOutlined
            onClick={() => editAddress(record)}
            style={{
              color: '#0071f0',
              cursor: 'pointer',
              fontSize: '16px',
              marginLeft: 5,
              marginTop: 2,
            }}
          />
        </div>
      ),
      checked: true, lock: false
    },
    {
      title: '区域编码',
      name: '区域编码',
      code: 'shopArea',
      width: 200,
      checked: true, lock: false
    },
    {
      title: (
        <Popover
          content={
            <div style={{ width: '300px' }}>
              <p>开启，则代表在该供应商的自发拿货商品是线下支付拿货方式</p>
              <p>关闭，则代表在该供应商的自发拿货商品，是线上支付拿货方式</p>
            </div>
          }
        >
          <div>
            线下支付
            <Iconfont type="iconwenhao1" />
          </div>
        </Popover>
      ),
      name: '线下支付',
      code: 'offlinePaySwitch',
      width: 120,
      render: (text, record) => (
        <Switch
          checkedChildren="已开启"
          unCheckedChildren="已关闭"
          checked={text == 1 ? true : false}
          onChange={(e) => upDateSwitch(e, record)}
        />
      ),
      checked: true, lock: false
    },
    {
      title: '门店顺序',
      name: '门店顺序',
      code: 'orderBy',
      width: 100,
      checked: true, lock: false
    },
    {
      title: '门店备注',
      name: '门店备注',
      code: 'shopRemark',
      // render: (_, record) => {
      //   return (
      //     <>
      //     <Popover
      //       content={
      //         <div className="custom-ant-popver-content">
      //           {record.shopRemark || ''}
      //         </div>
      //       }
      //     >
      //       <span className="textOverflowMultiTwo">
      //         {record.shopRemark || ''}
      //       </span>
      //     </Popover>
      //     <EditOutlined
      //       onClick={() => editAddressRemark(record)}
      //       style={{
      //         color: '#0071f0',
      //         cursor: 'pointer',
      //         fontSize: '16px',
      //         marginLeft: 5,
      //         marginTop: 2,
      //       }}
      //     />
      //     </>
      //   );
      // },
      width: 200,
      checked: true, lock: false
    },
    {
      title: '拿货员',
      name: '拿货员',
      code: 'takeUser',
      width: 120,
      checked: true, lock: false
    },
    {
      title: '退货员',
      name: '退货员',
      code: 'refundUser',
      width: 120,
      checked: true, lock: false
    },
    {
      title: '操作',
      name: '操作',
      key: 'opera',
      code: 'opera',
      lock: true,
      width: 120,
      render: (_, record) => (
        <span className="opera-span-common">
          <span onClick={() => handleEditOperator(record)}>编辑</span>
          <i>|</i>
          <span
            onClick={() => {
              handleRemark(1, record);
            }}
          >
            备注
          </span>
        </span>
      ),
      checked: true,
    },
  ];
  const [loading, setLoading] = useState(false);
  const [visibleList, setVisibleList] = useState('');

  const [pageConfig, setPageConfig] = useState({
		columns,//订单列数据
		isExistWeight: false,//操作设置，是否读取订单重量
	})

  useEffect(() => {
		getPageConfig();
	}, [])

  	//获取页面的配置信息
	const getPageConfig = async () => {
		setLoading(true);
		const params = {
			code: 'supplyPageConfigCode',
		}
		const { success, data = {} } = await getFieldConfig(params);
		if (success) {
			const { param = '' } = data;
			if (param) {
				setPageConfig(JSON.parse(param));
			}
		}
		setLoading(false)
	}

  	//更新配置文件
	const updatePageConfig = async (keys, val, cb) => {
    // val = val.filter(item => item.name != '企业微信接收人')
		const obj = {
			...pageConfig,
			[keys]: val
		}
		const { success } = await updateFieldConfig({
			code: 'supplyPageConfigCode', // mof变量
			param: JSON.stringify(obj)
		});
		if (success) {
			setPageConfig(obj);
		}
		cb && cb(success);
	}

  	//列设置props
	const EditColumnsProps = {
		initColumns: columns.map(item => {
      const {title, render, ...rest} = item
      return rest
    }),
		realColumns: pageConfig.columns.map(item => {
      const {title, render, ...rest} = item
      return rest
    }),
		updatePageConfig,
		handleCancel() {
			setVisibleList(null);
		},
		handleOk() {
			setVisibleList(null);
		},
	}

  //根据不同的offlinePaymentShow渲染展示列表列
  const renderCoulumns = () => {
    if (!offlinePaymentShow) {
      const index = findIndex(columns, ['code', 'offlinePaySwitch']);
      columns.splice(index, 1);
    }
    if (showRobot && !columns.some(item => item.name == '企业微信接收人')) {
      columns.splice(columns.length - 1, 0, {
        title: (
          <div>
            <span>企业微信接收人</span>
            <Popover
              content={
                <span style={{ display: 'block', width: '186px' }}>
                  需要先拿到企业微信推送消息的用户id，在此字段维护供应商对应用户id；每天20点向对应用户推送未拿货信息，用户需要手动将汇总的推送消息发送至对应供应商群
                </span>
              }
              title={null}
            >
              <QuestionCircleOutlined
                style={{ color: '#999', marginLeft: '8px' }}
              />
            </Popover>
          </div>
        ),
        name: '企业微信接收人',
        code: 'wechatUserId',
        width: 220,
        checked: true,
        lock: false,
        render: (text, record) => (
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              justifyContent: 'between-around',
            }}
          >
            <Popover content={<div>{text}</div>}>
              <div className={styles.customize}>{text}</div>
            </Popover>
            <EditOutlined
              onClick={() => handlePushRobot(record)}
              style={{
                color: '#0071f0',
                cursor: 'pointer',
                fontSize: '16px',
                marginLeft: 5,
                marginTop: 2,
              }}
            />
          </div>
        ),
      })
    }
    // if(is_zjf_user == 'true') {
    //     columns.splice(16, 0 , {
    //         title: '拿货员（代拿）',
    //         code: 'daiNaUser',
    //         key: 'daiNaUser',
    //         width: 150,
    //       })
    // } else {
    //     columns.splice(10, 0 , {
    //         title: '是否开启代拿',
    //         code: 'daiNaSwitch',
    //         key: 'daiNaSwitch',
    //         width: 150,
    //         render: (text, record) => <span>{text && text == 1 ? '开启': '关闭'}</span>
    //     })
    // }

    console.log('pageConfig.columns', columns)
    return columns.filter(item => {
      const obj = pageConfig.columns.filter(obj => obj.code == item.code)[0]
      item.width = obj?.width // 后台记录列宽，设置到前端
      item.lock = obj?.lock // 列锁定fixed
      return obj?.checked // 过滤checked为false的列
    })
    // return columns.filter(item => item.checked); 
  };

  // 备注弹框操作
  const handleRemark = (type, record = {}) => {
    setNote(record.shopRemark || '');
    if (type == 1) {
      setVisibleNote(true);
      setLength(record.shopRemark.length || 0);
      setId([
        {
          id: record.id,
          storeId: record.storeId,
        },
      ]);
    } else {
      if (selectedRow.length == 0) {
        Modal.info({
          content: '请先选择门店！',
        });
        return;
      }
      setId([]);
      setVisibleNote(true);
    }
  };

  // 修改拿货员&退货员操作
  const handleEditOperator = (record = {}, type = 0) => {
    if (!isEmpty(record)) {
      //单个
      setRoleType(type);
      setItem(record);
      setVisible(true);
    } else {
      //批量
      if (selectedRow.length == 0) {
        Modal.info({
          content: '请先选择门店！',
        });
        return;
      }
      setRoleType(type);
      setItem({});
      setVisible(true);
    }
  };

  const handleSetPrint = () => {
    //批量
    if (selectedRow.length == 0) {
      Modal.info({
        content: '请先选择门店！',
      });
      return;
    }
    setPrintVisible(true);
  }

  const handleSetPay = () => {
    //批量
    if (selectedRow.length == 0) {
      Modal.info({
        content: '请先选择门店！',
      });
      return;
    }
    setPayVisible(true);
  }

  //批量设置代拿
  const handleBatchSetDaina = (val) => {
    setRoleType(val);
    if (val == 'daifaSelect') { //所选
      if (selectedRow.length == 0) {
        Modal.info({
          content: '请先选择门店！',
        });
        return;
      }
      setVisible(true);
      setItem({});
    } else { //筛选
      setVisible(true);
    }
  }

  const StoreEditModalProps = {
    item,
    visible,
    roleList,
    totalAreaList,
    type: roleType,
    selectedRow,
    listData: data,
    handleOk() {
      handleStoreList();
    },
    handleCancel() {
      setVisible(false);
      setItem({});
    },
    clearSelect,
    total,
    query,
    showDaifaTool
  };

  	//保存列款配置
	const saveColumnWidth = (val) => {
		pageConfig.columns.map((v, i) => {
			//忽略选择列
			v.width = val[i+1];
		})
    console.log(1111, pageConfig.columns)
		updatePageConfig('columns', pageConfig.columns)
	}

  //表格组件
  const TableRenderProps = {
    data,
    rowKey: 'listKey',
    columns: renderCoulumns(),
    style: {
      height: `calc(100vh - ${headerHeight + btnHeight + 196}px)`
    },
    checkOption: {
      value: selectedRowId,
      onChange(val) {
        const arr = data.filter(v => val.includes(v.listKey)).map(v => {
          return {
            id: v.id,
            storeId: v.storeId,
          }
        })
        updateSelectedRowId(val);
        updateSelectRow(arr);
      }
    },
    columnResizeOption: {
			onChangeSizes: debounce(saveColumnWidth, 1000)
		},
    pageConfig: {
      pages,
      selectTotal: selectedRowId.length,
      handlePageSize(page, size) {
        setPages({
          ...pages,
          current: page,
          pageSize: size
        });
      }
    }
  }

  const StoreNotesModalProps = {
    selectedRow: !isEmpty(id) ? id : selectedRow,
    shopRemark: note,
    length,
    visible: visibleNote,
    handleOk: () => {
      handleStoreList();
      updateSelectRow([]);
      updateSelectedRowId([]);
      setVisibleNote(false);
    },
    handleCancel: () => {
      setVisibleNote(false);
    },
    onChange: (e) => {
      setLength(e.target.value.length);
    },
  };

  const editAddress = (record) => {
    setAddress(record.shopCustomAddress);
    setStoreId(record.storeId);
    setCustomizeVisible(true);
    setItem(record);
  };
  const editAddressRemark = (record) => {
    setShopRemark(record.shopRemark);
    setStoreId(record.storeId);
    setCustomizeVisibleRemark(true);
    setItem(record);
  };

  //企微推送机器人
  const handlePushRobot = (record) => {
    setItem(record);
    setRobotVisible(true);
  };

  //批量企微推送机器人
  const handleBatchPushRobot = () => {
    if (selectedRow.length) {
      setRobotVisible(true);
    } else {
      Modal.info({
        content: '请先选择门店！',
      });
    }
  }

  const customizeProps = {
    customizeVisible,
    customizeCancel: function () {
      setCustomizeVisible(false);
      setItem({});
    },
    handleStoreList,
    address,
    storeId,
    item
  };
  const customizePropsRemark = {
    customizeVisibleRemark,
    customizeCancel: function () {
      setCustomizeVisibleRemark(false);
      setItem({});
    },
    handleStoreList,
    shopRemark,
    storeId,
    item
  };

  const sortCodeModalProps = {
    visible: visibleSort,
    handleOk() {
      queryAreaCodeList();
      handleStoreList();
      setVisibleSort(false);
    },
    handleCancel() {
      queryAreaCodeList();
      setVisibleSort(false);
    },
  };

  //抵扣开关批量设置开关
  const switchModalProps = {
    visible: visibleSwitch,
    handleOk(bool) {
      updateDeductionSwitch(undefined, bool ? 1 : 0)
    },
    handleCancel() {
      setVisibleSwitch(false);
    }
  }

  //批量设置推送打印
  const BatchSetPrintProps = {
    visible: printVisible,
    handleOk(val) {
      batchSetPrintPush(val).then((res) => {
        if (val) {
          batchUpdateUnpickDisplayFunc(1)
        }
      });
    },
    handleCancel() {
      setPrintVisible(false);
    }
  };

  //企微群推送机器人
  const PushRobotProps = {
    visible: robotVisible,
    item,
    selectedRow,
    handleCancel() {
      setRobotVisible(false);
      setItem({});
    },
    handleOk() {
      setRobotVisible(false);
      setItem({});
      handleStoreList();
    }
  }

  // 待拿货数据同步 批量
  const handleDataSync = () => {
    //批量
    if (selectedRow.length == 0) {
      Modal.info({
        content: '请先选择门店！',
      });
      return;
    }
    setDataSyncVisible(true);
  }

  const batchUpdateUnpickDisplayFunc = async (value) => {
    let params = {
      "storeIds": selectedRow.map(item => item.storeId),
      "unpickDisplay": value
    }
    const { data, success } = await batchUpdateUnpickDisplay(params);
    if (success) {
      const { failCount, successCount } = data;
      if (failCount == '0') {
        Modal.info({
          content: '设置成功'
        })
      } else {
        Modal.info({
          content: (<>
            <div>修改成功 <span style={{ color: 'red' }}>{successCount}</span> 条   失败 <span style={{ color: 'red' }}>{failCount}</span> 条 </div>
            <div style={{ paddingLeft: 40 }}>自动推送订单打印开启状态下，不允许关闭拿货数据同步</div>
          </>)
        })
      }
      handleStoreList();
    }
  }


  //批量设置线下支付
  const batchUpdatePayStatus = async (val) => {
    const params = {
      storeIds: selectedRow.map(item => item.storeId),
      offlinePaySwitch: val ? 1 : 0
    }
    START_LOADING();
    const { success } = await batchUpdateOfflinePaySwitch(params);
    END_LOADING();
    if (success) {
      message.success('操作成功');
      setPayVisible(false);
      handleStoreList();
    }
  }

  //批量待拿货数据同步
  const dataSyncModalProps = {
    visible: dataSyncVisible,
    handleOk(value) {
      setDataSyncVisible(false);
      // handleStoreList();
      // Modal.info({
      //   content: '设置成功'
      // })
      batchUpdateUnpickDisplayFunc(value);

    },
    handleCancel() {
      setDataSyncVisible(false);
    }
  }

  //批量设置线下支付
  const BatchSetPayProps = {
    visible: payVisible,
    handleOk(val) {
      batchUpdatePayStatus(val);
    },
    handleCancel() {
      setPayVisible(false);
    }
  };

  //点击导入的渲染函数
  const renderImport = (children) => {
    return (
      <>
      
      <Popover
        content={
          <div style={{ width: '250px' }}>
            为确保导入数据准确，请使用导出的列表进行编辑修改在进行导入
          </div>
        }
      >
        <Upload
          name="file"
          headers={headers}
          data={{ type: 'QINIU' }}
          accept=".xls,.xlsx"
          action={`${httpChange(UPLOAD_SERVER)}/zjf-oms/files/uploadFile`}
          onChange={handleTableImport}
          showUploadList={false}
        // onRemove={handleRemove}
        >
          {children}
        </Upload>
      </Popover>
      
      {/* <BatchImport /> */}
      </>
    )
  }

  //操作按钮
  const btnArr = [
    { elType: 'button', text: '批量备注', onClick: handleRemark },
    { elType: 'button', text: '分配拿货员', onClick: () => handleEditOperator({}, 1) },
    { elType: 'button', text: '分配退货员', onClick: () => handleEditOperator({}, 2) },
    { elType: 'button', text: '批量设置区域编码', onClick: () => handleEditOperator({}, 3) },
    { elType: 'button', text: '区域编码配置及排序', onClick: () => setVisibleSort(true) },
    { elType: 'button', text: '退款抵扣', onClick: () => setVisibleSwitch(true) },
    { elType: 'button', text: '导出列表', onClick: handleTableExport },
    { elType: 'button', text: '导入数据', wrapFunc: renderImport },
    { elType: 'button', text: '批量设置推送打印', onClick: handleSetPrint },
    { elType: 'button', text: '待拿货数据同步', onClick: handleDataSync },
    { elType: 'button', text: '批量设置企业微信接收人', hide: showRobot ? false : true, onClick: handleBatchPushRobot },
    { elType: 'button', text: '线下支付', hide: offlinePaymentShow ? false : true, onClick: handleSetPay },
  ]


  return (
    <>
      <div className='global-page-wrap'>
        <div ref={btnEl}>
          <OperaBtnRender style={{ marginBottom: '12px' }} btnArr={btnArr} />
          {/* <div style={{float: 'right', marginBottom: 10}}>
            <Button type="text" onClick={() => setVisibleSort(true)}>
              <Iconfont type="icona-lujing12" />
              区域编码配置和排序
            </Button>
            <Button type="text" onClick={() => setVisibleList('editColumns')}>
              <Iconfont type="icona-lujing12" />
              列表设置
            </Button>
          </div> */}
        </div>
        <TableRender {...TableRenderProps} />
      </div>
      {visible && <StoreEditModal {...StoreEditModalProps} />}
      {visibleNote && <StoreNotesModal {...StoreNotesModalProps} />}
      {customizeVisible && <CustomizeModal {...customizeProps} />}
      {customizeVisibleRemark && <CustomizeModalRemark {...customizePropsRemark} />}
      {visibleSort && <SortAreaCodeModal {...sortCodeModalProps} />}
      {visibleSwitch && <BatchSetSwitch {...switchModalProps} />}
      {printVisible && <BatchSetPrint {...BatchSetPrintProps} />}
      {robotVisible && <PushRobot {...PushRobotProps} />}
      {dataSyncVisible && <DataSyncModal {...dataSyncModalProps} />}
      {payVisible && <BatchSetPay {...BatchSetPayProps} />}
      {visibleList == 'editColumns' && <EditColumns {...EditColumnsProps} />}
      <CommonLoading loading={loading} />
    </>
  );
};

export default StoreList;